package com.example.plugins

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.example.data.model.Response
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*

const val jwtAudience = "http://0.0.0.0:8080/hello"
const val jwtDomain = "http://0.0.0.0:8080/"
const val jwtRealm = "FunASMR"
const val jwtSecret = "fanketlyfanketlyfanketly"

fun Application.configureSecurity() {
    // Multiplatform
    // Please read the jwt property from the config file if you are using EngineMain
    authentication {
        jwt {
//            realm = jwtRealm
            verifier(
                JWT
                    .require(Algorithm.HMAC256(jwtSecret))//jwtSecret用于在JWT的签名部分与头部一起进行哈希计算，以确保JWT的安全性。只有拥有正确secret的一方才能验证JWT的有效性
                    .withAudience(jwtAudience)//希望谁接收
                    .withIssuer(jwtDomain)//签发者
                    .build()
            )
            validate { credential ->//对 JWT 载荷执行额外的验证
                if (credential.payload.audience.contains(jwtAudience)) JWTPrincipal(credential.payload) else null
            }
            challenge { defaultScheme, realm ->//配置在身份验证失败时发送的响应。
                call.respond(HttpStatusCode.Unauthorized, Response("Token无效或已过期", false, null))
            }
        }
    }
}
